<template>
  <div class="app-container">
    <div class="serach-container">
      <div class="search-inputs">
        <el-form :inline="true" :model="complexForm" class="demo-form-inline" label-position="right" label-width="70px">
          <el-form-item label="大区">
            <el-select v-model="complexForm.bigAreaCode" clearable placeholder="请选择大区" @change="complexForm.provinceCode = '', complexForm.cityCode = '', $forceUpdate()">
              <el-option v-for="(item, index) in regions" :key="index + '_' + item.bigAreaCode" :label="item.bigAreaName" :value="item.bigAreaCode" />
            </el-select>
          </el-form-item>
          <el-form-item label="省份">
            <el-select v-model="complexForm.provinceCode" filterable clearable placeholder="请选择省份" @change="complexForm.cityCode = '', $forceUpdate()">
              <el-option v-for="(item, index) in provinceOptions" :key="index + '_' + item.provinceCode" :label="item.provinceName" :value="item.provinceCode" />
            </el-select>
          </el-form-item>
          <el-form-item label="城市">
            <el-select v-model="complexForm.cityCode" filterable clearable placeholder="请选择城市" @change="$forceUpdate()">
              <el-option v-for="(item, index) in cityOptions" :key="index + '_' + item.cityCode" :label="item.cityName" :value="item.cityCode" />
            </el-select>
          </el-form-item>
          <el-button type="primary" @click="queryTableList">查询</el-button>
          <el-button @click="handelRest">重置</el-button>
        </el-form>
      </div>
    </div>
    <div class="section-container">
      <el-table v-loading="listLoading" size="mini" :data="tables.data" border fit highlight-current-row style="width: 100%" height="600">
        <el-table-column type="index" label="序号" width="50" align="center" />
        <el-table-column v-for="item in tables.columns" :key="item.key" align="center" :show-overflow-tooltip="true" :width="item.width" :label="item.lable" header-align="center">
          <template slot-scope="{row}">
            <div v-if="item.key === 'status'">
              <el-switch v-model="row.status" :active-value="1" :inactive-value="0" @change="toggleStatus(row)" />
            </div>
            <span v-else-if="item.key === 'effectiveEndTime'">{{ row | effectiveEndTimeFilter }}</span>
            <div v-else-if="item.key === 'source'">
              {{ row[item.key] == 1 ? '手动添加' : '系统识别' }}
            </div>
            <span v-else>{{ row[item.key] }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="160" fixed="right">
          <template slot-scope="{row}">
            <div class="actions-columns">
              <el-button
                type="text"
                size="small"
                @click="handelEdit(row)"
              >
                修改
              </el-button>
              <el-button
                type="text"
                size="small"
                :disabled="row.source == 0"
                @click="handelDelete(row)"
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <pagination :total="total" :page.sync="pages.page" :limit.sync="pages.limit" @pagination="changePages" />
    </div>
    <white-dialog ref="whiteDialog" @reload="reload"/>
  </div>
</template>

<script>
import { queryWhiteListCity, deleteWhiteListCity, switchWhiteListCity, queryWhiteListCityTrees } from '@/api/crossRegionalMonitoring'
import Pagination from '@/components/Pagination'
import whiteDialog from './whiteDialog'
import { getStorageByKey, unique_arr_by_key, fomatComfirmStr } from '@/utils/public'
export default {
  name: 'FenceList',
  components: { Pagination, whiteDialog },
  data() {
    return {
      tables: {
        columns: [
          { lable: '城市', key: 'cityName', align: 'center' },
          { lable: '省份', key: 'provinceName', align: 'center' },
          { lable: '大区', key: 'bigAreaName', align: 'center' },
          { lable: '数据来源', key: 'source', align: 'center' },
          { lable: '有效时间', key: 'effectiveEndTime', width: '240px', align: 'center' },
          { lable: '备注', key: 'remarks', align: 'center' },
          { lable: '状态', key: 'status', width: '100px', align: 'center' }
        ],
        data: []
      },
      pages: {
        pageNum: 1,
        pageSize: 20
      },
      total: 0,
      listLoading: true,
      complexForm: {},
      isMore: false,
      activeIndex: 0,
      regions: []
    }
  },
  filters: {
     // 有效时间
    effectiveEndTimeFilter(row) {
      const { startTime, effectiveEndTime, createTime } = row
      let effectiveEndTimeStr = ''
      if (startTime && effectiveEndTime) {
        effectiveEndTimeStr = `${startTime}至${effectiveEndTime}`
      } else if (startTime && !effectiveEndTime) {
        effectiveEndTimeStr = `${startTime}至永久`
      } else if (!startTime && effectiveEndTime) {
        effectiveEndTimeStr = `${createTime}至${effectiveEndTime}`
      } else {
        effectiveEndTimeStr = '永久有效'
      }
      return effectiveEndTimeStr
    }
  },
  computed: {
    // 省份下拉选项 跟随所选大区而变化
    provinceOptions() {
      if (this.regions && this.regions.length) {
        const currentBigArea = this.regions.filter(item => this.complexForm.bigAreaCode === item.bigAreaCode)
        const allProvince = this.regions.reduce((newArr, current) => {
          return newArr.concat(current.provinceList)
        }, [])
        if (currentBigArea.length) return unique_arr_by_key('provinceCode', currentBigArea[0].provinceList)
        return unique_arr_by_key('provinceCode', allProvince)
      } else {
        return []
      }
    },
    // 城市下拉选项 跟随所选省份而变化
    cityOptions() {
      const currentProvince = this.provinceOptions.filter(item => this.complexForm.provinceCode === item.provinceCode)
      if (currentProvince.length) return currentProvince[0].cityDtoList
      const allCity = this.provinceOptions.reduce((newArr, current) => {
        return newArr.concat(current.cityDtoList)
      }, [])
      return allCity
    }
  },
  created() {
    this.queryTableList()
    this.queryWhiteListCityTreesAsOptions()
  },
  methods: {
    reload() {
      this.queryTableList()
      this.queryWhiteListCityTreesAsOptions()
    },
    async queryWhiteListCityTreesAsOptions() {
      const { data } = await queryWhiteListCityTrees({ type: 2 })
      this.regions = data.bigAreaList || getStorageByKey('regionsMap')
    },
    changePages(params) {
      this.pages = { ...params }
      this.queryTableList()
    },
    async queryTableList() {
      this.listLoading = true
      const { data } = await queryWhiteListCity(this.formatParams())
      const items = data
      this.tables.data = items.list
      this.total = items.total
      this.listLoading = false
    },
    formatParams() {
      const params = { ...this.complexForm, ...this.pages }
      return params
    },
    // 清空复杂查询条件
    handelRest() {
      for (const key in this.complexForm) {
        this.complexForm[key] = ''
      }
    },
    toggleStatus(row) {
      const { startTime, effectiveEndTime, createTime, id, status } = row
      const params = { id }
      const confirmStr = fomatComfirmStr(startTime, effectiveEndTime, createTime, status)
      this.$confirm(confirmStr, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        switchWhiteListCity(params).then((res) => {
          this.$message({
            type: 'success',
            message: '操作成功'
          })
          this.queryTableList()
        })
      }).catch(() => {
        row.status = status ? 0 : 1   
      });
    },
    handelEdit(row) {
      this.$refs.whiteDialog.handelEdit(row)
    },
    handelDelete(row) {
      console.log(row)
      this.$confirm('此操作将删除白名单城市，您确认要继续吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const params = row.id
        deleteWhiteListCity(params).then((res) => {
          console.log(res)
          this.queryTableList()
        })
        // this.$message({
        //   type: 'success',
        //   message: '已成功删除该电子围栏!'
        // })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    handelAdd() {
      this.$refs.whiteDialog.handelAdd()
    }
  }
}
</script>
<style scoped>
  ::v-deep .actions-columns .el-button{
    padding: 0px;
  }
</style>
<style lang="scss" scoped>
  ::v-deep .el-form-item .el-form-item__content{
            width: 200px;
          }
  .record-header, .record-title {
    font-family: 'PingFangSC-Semibold', 'PingFang SC Semibold', 'PingFang SC', sans-serif;
    font-weight: 650;
    font-style: normal;
  }
  .record-header {
    font-size: 22px;
    text-align: center;
    line-height: 50px;
  }
  .record-title{
    font-size: 14px;
    text-align: left;
    line-height: 30px;
    background: #f1f1ff;
    padding: 0 15px;
  }
  .serach-container{
    width: 100%;
    display: flex;
    justify-content: space-between;
    .search-inputs{
      width: 90%;
    }
  }
  .tool-container{
    width: 100%;
    display: flex;
    justify-content: space-between;
    line-height: 30px;
    .toggle-warning{
      font-weight: bold;
    }
    .toggle-alarm{
        display: flex;
        margin-bottom: 20px;
        font-size: 13px;
        font-family: 'PingFangSC-Regular', 'PingFang SC', sans-serif;
        font-weight: 400;
        font-style: normal;
        cursor: pointer;
        div{
          width: 103px;
          border: 1px solid rgba(121, 121, 121, 1);
          text-align: center;
        }
        :first-of-type{
          border-top-left-radius: 5px;
          border-bottom-left-radius: 5px;
          border-right: none
        }
        :last-of-type{
          border-top-right-radius: 5px;
          border-bottom-right-radius: 5px;
        }
        .isActive{
          color: #fff;
          background: rgba(5, 167, 171, 1);
          border-color: rgba(5, 167, 171, 1);
        }
    }
  }
</style>
